/****************************************************
 * Description: ServiceImpl for 菜单
 * Copyright:   Copyright (c) 2013
 * Company:     beiwaionline
 * @author      bfsu
 * @version     1.0
 * @see
	HISTORY
    *  2013-08-08 bfsu Create File
**************************************************/

package com.bfsuol.bfsuolframework.security.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bfsuol.bfsuolframework.security.dao.MenuMapper;
import com.bfsuol.bfsuolframework.security.dao.Menu;
import com.bfsuol.bfsuolframework.security.entity.dto.MenuDTO;
import com.bfsuol.bfsuolframework.security.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper,Menu> implements MenuService {

    @Autowired
    private MenuMapper menuMapper;


    /*
     * (non-Javadoc)
     * @see MenuService#deleteMenu(Menu)
     */
	public boolean deleteMenu(Long menuId) {
		if(null == menuId)
			return false;
		List<Menu> menus = menuMapper.selectList(Wrappers.<Menu>lambdaQuery().eq(Menu::getParentId, menuId));//查找子菜单的id为此菜单的id:memuid
		if(menus.size() <= 0){//如果没有子菜单直接删除此菜单
			menuMapper.deleteById(menuId);
			return true;
		}else{
			for(Menu menu : menus){//如果当前菜单有子菜单，遍历他的子菜单
				this.deleteMenu(menu.getId());//递归调用，寻找子菜单里是否还有子菜单,并删除其中的子菜单
			}
			menuMapper.deleteById(menuId);//删除顶端的菜单
			return true;
		}
	}

	@Override
	public List<Menu> findAll() {
		return menuMapper.selectList(Wrappers.<Menu>lambdaQuery().eq(Menu::getIsEnabled, 100101));
	}

	@Override
	public List<MenuDTO> getCategoryMenus() {
		List<MenuDTO> parentMenus = findParentMenus();
		if(parentMenus != null && parentMenus.size() > 0){
			for(MenuDTO parentMenu : parentMenus){
				List<MenuDTO> childMenus = findChildMenus(parentMenu.getId());
				parentMenu.setSubMenus(childMenus);
			}
			return parentMenus;
		}
		return parentMenus;
	}

	@Override
	public List<MenuDTO> findParentMenus() {
		List<Menu> menus = menuMapper.selectList(Wrappers.<Menu>lambdaQuery().isNull(Menu::getParentId));
		return MenuDTO.convert(menus);
	}

	@Override
	public List<MenuDTO> findChildMenus(Long parentId) {
		List<Menu> menus = menuMapper.selectList(Wrappers.<Menu>lambdaQuery().eq(Menu::getParentId,parentId));
		return MenuDTO.convert(menus);
	}


}